# coding:utf-8

import aiohttp


class APIRequest:
    def __init__(self, base_url=None):
        self.base_url = base_url
        self.session = None

    async def __aenter__(self):
        self.session = aiohttp.ClientSession()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.session.close()

    async def request(self, method, url, data=None, headers=None, params=None):
        """
        :param method:
        :param path:
        :param data:
        :param headers:
        :param params:
        :return:
        """
        url = url
        if self.base_url:
            url = f"{self.base_url}/{url}"

        async with self.session.request(
                method=method, url=url, headers=headers, data=data, params=params
        ) as response:
            try:
                data = await response.json()
            except Exception:
                data = await response.text()
            headers = {k: v for k, v in response.headers.items()}
            status = response.status
            new_response = {
                "data": data,
                "headers": headers,
                "status": status
            }
            return new_response
